package top.misspro.valheimadminsocket.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import top.misspro.valheimadminsocket.exception.HandlerNotFoundException;
import top.misspro.valheimadminsocket.factory.HandlerStruct;
import top.misspro.valheimadminsocket.factory.ServerActionFactory;
import top.misspro.valheimadminsocket.factory.ServerEventFactory;
import top.misspro.valheimadminsocket.message.Action;
import top.misspro.valheimadminsocket.message.Request;
import top.misspro.valheimadminsocket.server.Client;
import top.misspro.valheimadminsocket.server.ServerContains;
import top.misspro.valheimadminsocket.util.ChannelUtils;
import top.misspro.valheimadminsocket.util.JSON;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author Evan
 */
@Slf4j
public class TextMessageHandle extends AbstractHandler<TextWebSocketFrame> {


    @Override
    protected void messageHandler(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        log.info("收到来自客户端（id）" + ctx.channel().id().asShortText() + "的文本信息：" + msg.text());
        try {
            //解析客户端请求
            Request request = JSON.parserObject(msg.text(), Request.class);
            //获得客户端
            Client client = ServerContains.CLIENT_MAP.get(ChannelUtils.getChannelId(ctx.channel()));

            HandlerStruct process = ServerActionFactory.getProcess(Action.Server.valueOf(request.getCode()));
            ServerContains.setThreadLocal(ctx.channel().id().asLongText());
            process.invoke();

        } catch (IOException e) {
            log.error("客户端消息解码失败");
            ChannelUtils.sendToClient(ctx.channel(), Action.Client.FAILED, null, "消息解码失败");
            e.printStackTrace();
        } catch (HandlerNotFoundException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            log.error("处理方法访问异常！请检查访问权限！");
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            log.error("处理方法内部发生未处理异常错误！");
            e.printStackTrace();
        }
    }
}
